<script setup lang="ts">
import ModelAreaBox from "@/views/Student/UseModel/component/model-area-box.vue";
import {defineProps, ref} from 'vue';
import type {UploadChangeParam, UploadFile} from 'ant-design-vue';
import {message} from 'ant-design-vue';
import {FileExcelOutlined, UploadOutlined} from '@ant-design/icons-vue';
import * as XLSX from "xlsx";
import * as dfd from "danfojs/dist/danfojs-browser/src/index"
import {postModelUploadDataForModel} from "@/apis/student";

const {fileType, showChart, modelFileType, modelId, testModelId} = defineProps({
  fileType: {
    type: String
  },
  showChart:{
    type: Boolean,
    default: false
  },
  modelFileType:{
    type: String
  },
  modelId:{
    type: Number
  },
  testModelId:{
    type: Number
  }
})
const handleChange = (info: UploadChangeParam) => {
  if (info.file.status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (info.file.status === 'done') {
    message.success(`${info.file.name} file uploaded successfully`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};
//文件上传设置
const fileList = ref([]);
const headers = {
  authorization: 'authorization-text',
};
//表格基础信息设置
let tableName=ref<string>('')
let tableData = ref<Array<any>>([])
let columns = ref<Array<any>>([])
let upBtn = ref<boolean>(false)
//模态框设置
const open = ref<boolean>(false);
const showModal = () => {
  if(!upBtn.value){
    message.warning("没有内容可以显示")
    return
  }
  open.value = true;
};
// AI检测
const handleOk = () => {
  if(!upBtn.value){
    message.warning("没有内容可以显示")
    return
  }
  open.value = true;
}
//图表绘制
const mackChart = (file: UploadFile<any>, x: string, y: string, id: string) => {
  if (showChart)
  dfd.readExcel(file)
      .then((df:any) => {
        df.plot(id).scatter({
          config: { x: x, y: y }
        })
      })
}
let valueX = ref<string>('')
let valueY = ref<string>('')
let fileData = ref<UploadFile<any>>();
const resetChart = (param:any,type:string) => {
  switch (type) {
    case 'x':
      valueX.value = param
      if (fileData.value)
      mackChart(fileData.value,valueX.value,valueY.value,'plot_div')
      break
    case 'y':
      valueY.value = param
      if (fileData.value)
        mackChart(fileData.value,valueX.value,valueY.value,'plot_div')
      break
    default:
      break
  }
  console.log(valueX.value, valueY.value)
}
const handleFileUp = (param: UploadChangeParam) => {
  //滞空
  tableName.value=''
  tableData.value=[]
  columns.value=[]
  descriptionsDate.value=[]
  // 解构文件
  const {file} = param
  fileData.value = file
  formData.append('file',fileData.value)
  tableName.value = file.name
  const reader:any = new FileReader();
  reader.onload = (e:any) => {
    //将传如的file读取出来
    const data = e.target.result;
    //读取（本地或网络）文件，并创建一个工作薄
    const workbook = XLSX.read(data, { type: 'binary' });
    const sheetName = workbook.SheetNames[0];
    const sheetData:Array<any> = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName])
    const endIndex = Object.keys(sheetData[0]).length-1
    columns.value = Object.keys(sheetData[0]).map((item:any,index:number)=> {
      if (index === 0) {
        return ({
          align: 'center',
          title: item,
          dataIndex: item,
          key: `${item}-${index}`,
          width: 120,
          resizable: true,
          minWidth: 120,
          fixed: "left"
        })
      }
      if(index === endIndex){
        return ({
          align: 'center',
          title: item,
          dataIndex: item,
          width: 120,
          resizable: true,
          minWidth: 120,
          key: `${item}-${index}`,
          fixed: "right"
        })
      }
      return ({
        align: 'center',
        title: item,
        dataIndex: item,
        width: 120,
        key: `${item}-${index}`,
      })
    })
    // 穿梭框设置
    getMock()
    sheetData.forEach(item => {
      tableData.value.push(item)
    })
    // tableData.value = sheetData
    upBtn.value = true
    // 图表初始化绘制
    valueX.value = columns.value[0].title
    valueY.value = columns.value[endIndex].title
    try {
      mackChart(file,valueX.value,valueY.value,'plot_div')
    } catch (e) {
      console.log(e)
    }

  };
  reader.readAsBinaryString(file);
}
const handleFileUpEro = () => {
  message.error("文件不符合类型")
}
// 构造上传文件
const formData = new FormData();
console.log(formData)
const handleFileUpClick = () => {
  if (!upBtn.value){
    message.warning("没有文件可以上传！")
    return
  }
  // 文件上传
  // postModelUploadDataForModel({
  //   modelId:+modelId,
  //   type: modelFileType,
  //   id: +modelId,
  //   selTrainFile:descriptionsDate.value
  // },fileData.value).then(res =>{
  //   console.log(res)
  // }).catch(err =>{
  //   console.log(err)
  // })
  message.success("文件上传到后端")
}
//穿梭框设置
interface MockData {
  key: string;
  title: string;
  description: string;
  chosen: boolean;
}
const mockData = ref<MockData[]>([]);
const targetKeys = ref<string[]>([]);
// 特征列存储
let descriptionsDate = ref<Array<any>>([])
const getMock = () => {
  const keys:any = [];
  const mData:any = [];
  columns.value.forEach((item)=>{
    const data = {
      key: item.key,
      title: item.title,
      description: item.dataIndex,
      chosen: item.align==='',
    }
    if (data.chosen) {
      keys.push(data.key);
    }
    mData.push(data);
  })
  mockData.value = mData;
  targetKeys.value = keys;
};
const filterOption = (inputValue: string, option: MockData) => {
  console.log("filterOption",inputValue, option)
  return option.description.indexOf(inputValue) > -1;
};
// 获取的特征列表
const handleChanges = (keys: string[], direction: string, moveKeys: string[]) => {
  descriptionsDate.value = []
  keys.forEach((item) => {
    //正则表示式去掉item最后一个-及内容
    const index = item.lastIndexOf("-")
    const label = item.slice(0, index)
    descriptionsDate.value.push(label)
  })
};
const handleSearch = (dir: string, value: string) => {
  console.log('search:', dir, value);
};
</script>

<template>
  <a-flex justify="space-between">
    <a-upload
        v-model:file-list="fileList"
        accept=".xls,.xlsx,.csv"
        :directory="false"
        :maxCount="1"
        name="trainFile"
        @reject="handleFileUpEro"
        :customRequest="handleFileUp"
        @drop="handleFileUp"
        action="#"
        :headers="headers"
    >
      <a-button>
        <FileExcelOutlined />
        选择{{fileType}}
      </a-button>
    </a-upload>
    <a-button @click="showModal">AI检测</a-button>
    <a-button @click="showModal">查看数据内容</a-button>
    <a-button @click="handleFileUpClick">
      <UploadOutlined />
      上传数据集
    </a-button>
  </a-flex>
  <model-area-box :title="`${tableName||'未选择数据集'}`">
    <a-row :gutter="16">
        <a-col :span="12">
          <a-transfer
              v-model:target-keys="targetKeys"
              :data-source="mockData"
              show-search
              :filter-option="filterOption"
              :render="(item:any) => item.title"
              @change="handleChanges"
              @search="handleSearch"
              pagination
              :locale="{ itemUnit: '项', itemsUnit: '项', notFoundContent: '列表为空', searchPlaceholder: '请输入搜索内容' }"
              :operations="['提取目标列', '剔除目标列']"
          >
          </a-transfer>
        </a-col>
        <a-col :span="12">
          <a-descriptions size="small" :title="`${tableName?tableName+'已选目标列':'未选择数据集'}`" bordered :column="5">
            <a-descriptions-item v-for="item in descriptionsDate">{{item}}</a-descriptions-item>
          </a-descriptions>
        </a-col>
      </a-row>
  </model-area-box>
  <model-area-box v-if="tableName && showChart" title="图像生成">
    <a-row>
      X轴：
      <a-radio-group v-model:value="valueX" name="radioGroupX">
        <a-radio v-for="item in columns" @click="resetChart(item.title,'x')" :value="item.title">{{item.title}}</a-radio>
      </a-radio-group>
    </a-row>
    <a-row>
      Y轴：
      <a-radio-group v-model:value="valueY" name="radioGroupY">
        <a-radio v-for="item in columns" @click="resetChart(item.title,'y')" :value="item.title">{{item.title}}</a-radio>
      </a-radio-group>
    </a-row>
    <div id="plot_div"></div>
  </model-area-box>
  <a-modal v-model:open="open"
           :mask="false"
           width="100%"
           wrap-class-name="full-modal"
           style="top: 20px"
           keyboard>
    <template #footer></template>
    <model-area-box :title="`${tableName||'未选择数据集'}`">
      <a-table :dataSource="tableData" :columns="columns" size="small" :scroll="{scrollToFirstRowOnChange:true, x: 1200, y: 520 }"/>
    </model-area-box>
  </a-modal>
</template>

<style scoped lang="scss">
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
  }
}
</style>
